package com.jqsoft.launcher.activity.setting;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.TiJiaoSFBean;
import com.jqsoft.launcher.activity.childCareManagement.XSEFollowUpRecordActivity3;
import com.jqsoft.launcher.activity.diabetesMellitus.DiabetesMellitusFollowUpActivity3;
import com.jqsoft.launcher.activity.highblood.HBPFollowUpRecordActivity3;
import com.jqsoft.launcher.activity.majorPsychosis.MajorPsychosisFollowUpActivity3;
import com.jqsoft.launcher.activity.pregnantWomen.PregnantWomenFollowUpActivity3;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.util.FileService;
import com.jqsoft.launcher.util.MessageTools;
import com.jqsoft.launcher.util.NetUtil;
import com.jqsoft.launcher.util.WebServiceUtils;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 提交随访信息页面
 * 
 * @author gujunqi date：2014-3-26
 */
public class SubmitInfoListActivity extends JQActivity implements
		OnClickListener {
	private final String tag = "SubmitInfoListActivity";
	private ListView tijiao_suifang_lv;// 列表
	private ListAdapter adapter;
	private TiJiaoSFBean obj;
	private CheckBox xzCheckbox;
	private Button quanxuan_btn, shangchuan_btn, chakan_btn, dete_btn;
	private List<TiJiaoSFBean> infoList = new ArrayList<TiJiaoSFBean>();
	private List<TiJiaoSFBean> tempList = new ArrayList<TiJiaoSFBean>();
	private int chakan;
	private String mangeType;

	@Override
	protected int getContentLayout() {
		return R.layout.submit_info_list;
	}

	@Override
	protected void initGui() {
		tijiao_suifang_lv = (ListView) findViewById(R.id.tijiao_suifang_lv);
		quanxuan_btn = (Button) findViewById(R.id.quanxuan_btn);
		quanxuan_btn.setOnClickListener(SubmitInfoListActivity.this);
		shangchuan_btn = (Button) findViewById(R.id.shangchuan_btn);
		shangchuan_btn.setOnClickListener(SubmitInfoListActivity.this);
		chakan_btn = (Button) findViewById(R.id.chakan_btn);
		dete_btn = (Button) findViewById(R.id.dete_btn);
		dete_btn.setOnClickListener(SubmitInfoListActivity.this);
		chakan_btn.setOnClickListener(SubmitInfoListActivity.this);
		// totalcount_bt=(Button) findViewById(R.id.totalcount_bt);
		// dangan_num_et=(EditText) findViewById(R.id.dangan_num_et);
		// name_et=(EditText) findViewById(R.id.name_et);
		// shengfenzheng_et=(EditText) findViewById(R.id.shengfenzheng_et);

	}

	@Override
	protected void initAction() {
		setGoBack();
		tijiao_suifang_lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				obj = (TiJiaoSFBean) tijiao_suifang_lv.getItemAtPosition(position);
				xzCheckbox = (CheckBox) view.findViewById(R.id.xuanzhong_cb);
				for (int i = 0; i < infoList.size(); i++) {
					infoList.get(i).setCheck(false);
				}
				if (xzCheckbox.isChecked()) {
					xzCheckbox.setChecked(false);
					obj.setCheck(false);
				} else {
					xzCheckbox.setChecked(true);
					obj.setCheck(true);
				}
				xzCheckbox.setChecked(true);
			 	adapter.notifyDataSetChanged();
				// xzCheckbox.setOnCheckedChangeListener(new
				// OnCheckedChangeListener(){
				//
				// @Override
				// public void onCheckedChanged(CompoundButton buttonView,
				// boolean isChecked) {
				// if(isChecked){
				// xzCheckbox.setChecked(false);
				// obj.setCheck(true);
				// }else{
				// xzCheckbox.setChecked(true);
				// obj.setCheck(false);
				// }
				//
				//
				// }
				//
				// });
				// obj.setCheck(true);
				// xzCheckbox.setChecked(true);
				// adapter.notifyDataSetChanged();
			}

		});
	}

	@Override
	protected void onResume() {
		initData();
		super.onResume();
	}

	@Override
	protected void initData() {
		setTitle("上传随访信息");
		mangeType = getIntent().getStringExtra("mangeType");
		loadWaitPanel();
		new Thread() {
			public void run() {
				// 初始化文件服务
				FileService fileService = new FileService(ctx);
				try {
					tempList.clear();
					tempList = fileService.getUserInfo("append.txt");
					infoList.clear();
					if (tempList.size() > 0) {
						//
						for (int i = 0; i < tempList.size(); i++) {
							if (tempList.get(i).getSuifangtype()
									.equals(mangeType)) {
								// 孕产妇保健随访
								// 高血压随访
								// 糖尿病患者随访
								// 重性精神疾病患者随访
								// 儿童保健随访
								infoList.add(tempList.get(i));
							}
						}
						myhandler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
					} else {
						dismissrogressBar();
					}

				} catch (Exception e) {
					dismissrogressBar();
				}
			}

		}.start();
	}

	private Handler myhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.MSG_LOAD_OVER:
				dismissrogressBar();
				if (infoList == null) {
					break;
				}
				adapter = new ListAdapter();
				tijiao_suifang_lv.setAdapter(adapter);
				break;
			case Constant.TIJIAO_OVER:
				dismissrogressBar();
				adapter.notifyDataSetChanged();
				break;
			case Constant.TIJIAO_ERROR:
				dismissrogressBar();
				Toast.makeText(SubmitInfoListActivity.this, "上传失败！",
						Toast.LENGTH_SHORT).show();
				break;
			case Constant.TIJIAO_SCCUSE:
				dismissrogressBar();
				Toast.makeText(SubmitInfoListActivity.this, "上传成功！",
						Toast.LENGTH_SHORT).show();
				adapter.notifyDataSetChanged();
				break;
			case Constant.DELETOK:
				Toast.makeText(SubmitInfoListActivity.this, "删除成功",
						Toast.LENGTH_SHORT).show();
				adapter.notifyDataSetChanged();
				break;
			}
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.quanxuan_btn:// 全选按钮
			if (infoList != null) {
				for (int i = 0; i < infoList.size(); i++) {
					infoList.get(i).setCheck(true);
				}
				adapter.notifyDataSetChanged();
			}
			return;
		case R.id.dete_btn:
			chakan = -1;
			if (yixuan() == 1) {
				Builder builder = new Builder(act);
				builder.setCancelable(false);
				builder.setTitle("温馨提示：");
				builder.setMessage("确认删除？");
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								new Thread() {
									public void run() {
										shanchu();
									};
								}.start();
							}
						});
				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// 客户取消更新，显示银行公告
							}
						});
				MessageTools.showDialog(builder);
			}
			 else {
				MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
			}
			break;
		case R.id.chakan_btn:
			// if(current_xzCheckbox==null){
			// MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
			// return;
			// }
			chakan = -1;
			if (yixuan() == 1) {
				// String sPersonID
				// String result=obj.getSuifangData();
				// JSONArray jsonArray1;
				// try {
				// jsonArray1 = new JSONArray(result);
				// for (int i = 0; i < jsonArray1.length(); ++i) {
				// JSONObject jsonData = (JSONObject) jsonArray1.get(i);
				// if (i == 0) {
				// // sPersonID=jsonData.getString("sPersonID");
				// }
				// }
				// } catch (Exception e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }

				if ("高血压随访".equals(obj.getSuifangtype())) {
					Intent intent = new Intent(act,
							HBPFollowUpRecordActivity3.class);
					Bundle bundle = new Bundle();
					bundle.putString("Tjdata", obj.getSuifangData());
					bundle.putString("sPersonID", obj.getsPersonID());
					bundle.putString("sNo", obj.getsNo());
					bundle.putString("sname", obj.getSname());
					bundle.putString("sCardNo", obj.getsCardNo());
					bundle.putInt("chakan", chakan);
					intent.putExtras(bundle);
					startActivity(intent);
				} else if ("重性精神疾病患者随访".equals(obj.getSuifangtype())) {
					Intent intent = new Intent(act,
							MajorPsychosisFollowUpActivity3.class);
					Bundle bundle = new Bundle();
					bundle.putString("Tjdata", obj.getSuifangData());
					bundle.putString("sPersonID", obj.getsPersonID());
					bundle.putString("sNo", obj.getsNo());
					bundle.putString("sname", obj.getSname());
					bundle.putString("sCardNo", obj.getsCardNo());
					bundle.putInt("chakan", chakan);
					intent.putExtras(bundle);
					startActivity(intent);
				} else if ("糖尿病患者随访".equals(obj.getSuifangtype())) {
					Intent intent = new Intent(act,
							DiabetesMellitusFollowUpActivity3.class);
					Bundle bundle = new Bundle();
					bundle.putString("Tjdata", obj.getSuifangData());
					bundle.putString("sPersonID", obj.getsPersonID());
					bundle.putString("sNo", obj.getsNo());
					bundle.putString("sname", obj.getSname());
					bundle.putString("sCardNo", obj.getsCardNo());
					bundle.putInt("chakan", chakan);
					intent.putExtras(bundle);
					startActivity(intent);
				} else if ("儿童保健随访".equals(obj.getSuifangtype())) {
					Intent intent = new Intent(act,
							XSEFollowUpRecordActivity3.class);
					Bundle bundle = new Bundle();
					bundle.putString("Tjdata", obj.getSuifangData());
					bundle.putString("sPersonID", obj.getsPersonID());
					bundle.putString("sNo", obj.getsNo());
					bundle.putString("sname", obj.getSname());
					bundle.putString("sCardNo", obj.getsCardNo());
					bundle.putInt("chakan", chakan);
					intent.putExtras(bundle);
					startActivity(intent);
				} else if ("孕产妇保健随访".equals(obj.getSuifangtype())) {
					Intent intent = new Intent(act,
							PregnantWomenFollowUpActivity3.class);
					Bundle bundle = new Bundle();
					bundle.putString("Tjdata", obj.getSuifangData());
					bundle.putString("sPersonID", obj.getsPersonID());
					bundle.putString("sNo", obj.getsNo());
					bundle.putString("sname", obj.getSname());
					bundle.putString("sCardNo", obj.getsCardNo());
					bundle.putInt("chakan", chakan);
					intent.putExtras(bundle);
					startActivity(intent);
				}

				// bundle.putSerializable(" TiJiaoSFBean", obj);
				// intent.putExtras(bundle);

			} else {
				MessageTools.showDialogOk(ctx, "请选择需要操作的数据,并且只能选择一项！");
			}
			break;

		case R.id.shangchuan_btn:// 上传按钮
			// String msg="您当前使用的网络为"+BphsConstants.NET_TYPE;
			if (!BphsConstants.isNetAvailable) {
				MessageTools.showDialogOk(ctx, "此功能暂不支持离线操作，请联网操作！");
				return;
			}
			if (yixuan() >= 1) {
				NetUtil.getNetType(act);
				Builder builder = new Builder(act);
				builder.setCancelable(false);
				builder.setTitle("温馨提示：");
				builder.setMessage(BphsConstants.NET_TYPE);
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								loadWaitPanel();
								new Thread() {
									public void run() {
										shangChuan();
									};
								}.start();
							}
						});
				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// 客户取消更新，显示银行公告
							}
						});
				MessageTools.showDialog(builder);
			} else {
				MessageTools.showDialogOk(ctx, "请选择需要操作的数据！");
			}
			return;
			 
			

		}
	}

	private int yixuan() {
		int yixuanNum = 0;
		if (infoList == null) {
			return 0;
		}
		for (int i = 0; i < infoList.size(); i++) {
			if (infoList.get(i).isCheck()) {
				chakan = i;
				yixuanNum++;
				obj = infoList.get(i);
			}
		}
		return yixuanNum;
	}
	public void shanchu(){
		for (int i = 0; i < infoList.size(); i++) {
			TiJiaoSFBean infoBean = infoList.get(i);
			if (infoBean.isCheck()) {
				infoList.remove(i);
				try {
					new FileService(ctx).removeFromRom2(i,mangeType ,"append.txt");
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				myhandler.sendEmptyMessage(Constant.DELETOK);
			}
		}
	}
	 

	public void shangChuan() {
		String methodNameKey = "", serviceURLKey = "";
		for (int i = 0; i < infoList.size(); i++) {
			TiJiaoSFBean infoBean = infoList.get(i);
			if (infoBean.isCheck()) {
				try {
					if ("高血压随访".equals(infoBean.getSuifangtype())) {
						methodNameKey = "AddHypertensionVisiting_METHOD";
						serviceURLKey = "GAddHypertensionVisiting_URL";
					} else if ("重性精神疾病患者随访".equals(infoBean.getSuifangtype())) {
						methodNameKey = "AddPsychosisPersonVisiting_METHOD";
						serviceURLKey = "AddPsychosisPersonVisiting_URL";
					} else if ("糖尿病患者随访".equals(infoBean.getSuifangtype())) {
						methodNameKey = "AddType2Diabetes_METHOD";
						serviceURLKey = "AddType2Diabetes_URL";
					} else if ("儿童保健随访".equals(infoBean.getSuifangtype())) {
						methodNameKey = "AddNewBorn_METHOD";
						serviceURLKey = "AddNewBorn_URL";
					} else if ("孕产妇保健随访".equals(infoBean.getSuifangtype())) {
						methodNameKey = "AddPostpartumVisiting_METHOD";
						serviceURLKey = "AddPostpartumVisiting_URL";
					}
					String methodName = BphsURL.getCommonPath(methodNameKey);
					String serviceURL = BphsURL.getCommonPath(serviceURLKey);
					// String methodName = "AddPsychosisPersonVisiting";
					// String serviceURL =
					// "http://60.171.146.122:9098/WebService/Andrews/PsychosisPersonWebService.asmx";
					String result = WebServiceUtils.requestByParams(methodName,
							infoBean.getSuifangData(), serviceURL);
					if (StringUtils.isNotBlank(result)) {
						JSONObject json = new JSONObject(result);
						String sResult = json.getString("sSuccess");
						if (sResult.equals("1")) {

							infoList.remove(i);
							new FileService(ctx).removeFromRom2(i, mangeType,
									"append.txt");
							// if (i==infoList.size()-1) {
							myhandler.sendEmptyMessage(Constant.TIJIAO_SCCUSE);
							// }Toast.makeText(SubmitInfoListActivity.this,"保存完成！",
							// Toast.LENGTH_SHORT).show();

						} else {
							myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
							// Toast.makeText(MajorPsychosisFollowUpActivity.this,
							// "保存失败！", Toast.LENGTH_SHORT).show();
						}
					} else {
						myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
						// Toast.makeText(MajorPsychosisFollowUpActivity.this,
						// "远程服务器故障！", Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					// myhandler.sendEmptyMessage(Constant.TIJIAO_ERROR);
					e.printStackTrace();
				}

			}

		}
		// infoList

	}

	private class ListAdapter extends BaseAdapter {

		public int getCount() {
			return infoList.size();
		}

		public Object getItem(int position) {
			return infoList.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(act);

			convertView = inflater.inflate(R.layout.submit_info_item, null);
			TextView dangan_num_tv = (TextView) convertView
					.findViewById(R.id.dangan_num_tv);
			TextView name_tv = (TextView) convertView
					.findViewById(R.id.name_tv);
			TextView shengfenzheng_tv = (TextView) convertView
					.findViewById(R.id.shengfenzheng_tv);
			TextView suifang_shijian_tv = (TextView) convertView
					.findViewById(R.id.suifang_shijian_tv);
			TextView suifang_type_tv = (TextView) convertView
					.findViewById(R.id.suifang_type_tv);
			CheckBox xuanzhong_cb = (CheckBox) convertView
					.findViewById(R.id.xuanzhong_cb);

			try {
				xuanzhong_cb.setChecked(infoList.get(position).isCheck());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			dangan_num_tv.setText(infoList.get(position).getsNo());
			name_tv.setText(infoList.get(position).getSname());
			shengfenzheng_tv.setText(infoList.get(position).getsCardNo());
			suifang_shijian_tv.setText(infoList.get(position).getDate());
			suifang_type_tv.setText(infoList.get(position).getSuifangtype());

			return convertView;
		}
	}
}
